<template>
<div>
  <div class="info-top">
    <a-row>
      <a-col :span="10" :style="{background: '#fff'}">
        <div class="table-btn-flex">
          <div>
            <a-radio-group v-model:value="activeKey" style="margin: 8px" @change="changeRadio">
              <a-radio-button value="1">合同信息</a-radio-button>
              <a-radio-button value="2">合同标签</a-radio-button>
            </a-radio-group>
          </div>
          <div  class="pdf-info-btn" v-if="activeKey === '1'">
            <a-button type="link" @click="editClick">
              <template #icon>
                <EditOutlined />
              </template>
              编辑
            </a-button>
            <a-button :style="{margin: '0 10px'}" type="link" v-if="isEdit" @click="saveClick">
              保存
            </a-button>
            <a-button type="link" v-if="isEdit" @click="cancelClick">
              取消
            </a-button>
          </div>
        </div>
        <div :style="{margin: '0 24px'}">
          <a-divider :style="{background: '#fff', margin: '0'}"/>
        </div>
        <div v-if="activeKey === '1'">
          <ContractDecriptions v-if="tabs === '1'"
                               :dataObj="resultObjData"
                               @saveEdit="onSaveEdit"
                               :isEdits="isEdit"
                               :isSaves="isSave"
                               @searchTxt="searchTxtPostion"/>
          <MianContractDecriptions v-if="tabs === '2'"
                                   @saveEdit="onSaveEdit"
                                   :isEdits="isEdit"
                                   :isSaves="isSave"
                                   :dataObj="resultObjData"
                                   @searchTxt="searchTxtPostion"/>
        </div>
        <div v-if="activeKey === '2'">
          <div class="info-right">
            <div class="pdf-search">
              <div class="pdf-head">
                <div class="pdf-title"></div>
                <div class="pdf-tip"></div>
              </div>
              <div class="pdf-input">
                <a-input placeholder="请输入标签搜索" v-model:value="searchLabel" @change="onSearchLabel">
                  <template #suffix>
                    <SearchOutlined @click="onSearchLabel" style="color: #0062AD" />
                  </template>
                </a-input>
                <div class="input-tip" v-if="contractLabels.length > 0">
                  <div class="tip-item" v-for="(item, index) in contractLabelsSearch" :key="item.id">
                    <div :style="{display: 'flex', width: '95%',cursor: 'pointer'}" @click="lablePosion(item)">
                      <TagsOutlined :style="{color: '#0062AD', marginRight: '5px'}"/>
                      <span class="tip-title-num">{{index + 1}}、</span>
                      <span class="tip-title">{{item.labelValue }}</span>
                      <span class="tip-detail">{{item.labelDetail }}</span>
                    </div>
                    <div>
                      <DeleteOutlined @click="deleteLable(item)" :style="{color: '#F5001D', marginLeft: '5px'}"/>
                    </div>
                  </div>
                </div>
                <EmptyDefault :style="{marginTop: '60px'}" v-else :descriptionInfo="'暂无合同标签'"/>
                <!--              <a-button type="link">-->
                <!--                <template #icon>-->
                <!--                  <PlusOutlined />-->
                <!--                </template>-->
                <!--                新增标签-->
                <!--              </a-button>-->
              </div>

            </div>

          </div>
        </div>
      </a-col>
      <a-col :span="14">
        <div class="info-middle">
          <div class="pdf-box">
            <div class="pdf-title">合同原件</div>
            <div class="pdf-file-box">
              <PdfTestInfo :originalContract="originalContract" :searchInfo="searchInfo"
                           :posionInfo="posionInfo"
                           :contractLabels="contractLabels"
                           @saveLabel="onSaveLabel"/>
            </div>
          </div>
          <div class="file-type">
            <div class="file-head">
              <div class="pdf-title">合同附件</div>
              <div>
                <a-button class="border-btn" @click="showModal">
                  <template #icon>
                    <CloudUploadOutlined />
                  </template>
                  上传
                </a-button>
              </div>
            </div>
            <div class="file-list">
              <div class="file-item" v-for="item in filesData" :key="item.id">
                <img v-if="item.url.includes('.docx')" src="@/assets/images/ResourceContract/word.png" alt="">
                <img v-else-if="item.url.includes('.doc')" src="@/assets/images/ResourceContract/word.png" alt="">
                <img v-else src="@/assets/images/ResourceContract/pdf.png" alt="">
                <div class="img-url">
                  <span >
                    <EyeOutlined @click="showWordhandleOk(item.url)"/>
                  </span>
                  <span :style="{paddingLeft: '20px'}">
                     <EditOutlined @click="editFile(item)"/>
                  </span>
                  <span :style="{position: 'absolute', top: '-31px', right: '-5px', color: 'rgba(51,51,51,0.7)'}">
                    <a-popconfirm
                        title="是否确认删除?"
                        ok-text="删除"
                        cancel-text="取消"
                        @confirm="deleteFileConfirm(item)"
                    >
                       <template #icon><question-circle-outlined style="color: #F5001D" /></template>
                        <CloseCircleFilled/>
                       </a-popconfirm>
                  </span>
                </div>
                <div class="file-name">
                  <span :style="{cursor: 'pointer', paddingRight: '10px'}" @click="dowloadFile(item.url)"> {{item.fileName}}</span>
                  <a-tooltip>
                    <template #title>
                      {{item.remark?item.remark : '无'}}
                    </template>
                    <QuestionCircleOutlined />
                  </a-tooltip>
                </div>
              </div>
            </div>
            <EmptyDefault v-if="filesData.length === 0" :descriptionInfo="'暂无合同附件'"></EmptyDefault>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
  <div class="info-bottom">
    <a-row :gutter="16">
      <a-col :span="18">
        <div class="bottom-table">
          <div class="pdf-title">{{tableTile}}</div>
          <div class="info-table">

            <a-table v-if="tabs === '1'" :columns="columns" :data-source="data"
                     :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                     :row-key="(record) => record.id"
                     :scroll="{ x: 500}">
            </a-table>
            <a-table v-if="tabs === '2'" :columns="mainColums" :data-source="mainMemoradumData"
                     :rowClassName="(record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                     :row-key="(record) => record.id"
                     :scroll="{ x: 500}">
              <template #bodyCell="{ column, text }">
                <template v-if="column.key === 'tags'">
                  <div class="table-btn-box">
                    <span class="table-btn btn-1" @click="goInfo(text.id)">查看</span>
                  </div>
                </template>
                <template v-if="column.key === 'tradeBody'">
                  <span v-for="item in tradeareas" :key="item.label">
                        <span v-if="item.value === text">{{item.label}}</span>
                    </span>
                </template>
                <template v-if="column.key === 'deliveryType'">
                  <span v-for="item in wayareas" :key="item.label">
                        <span v-if="item.value === text">{{item.label}}</span>
                    </span>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </a-col>
      <a-col :span="6">
        <div class="pdf-state">
          <div class="pdf-title">动态</div>
          <EmptyDefault v-if="timelineData.length === 0" :descriptionInfo="'暂无动态'"></EmptyDefault>
          <div class="timeline-box" v-else>
            <a-timeline>
              <a-timeline-item v-for="items in timelineData" :key="items.conId">
                <div class="timeline-title">{{items.optType}}：{{items.optPersonnel}}</div>
                <div class="timeline-time">{{items.optTime}}</div>
              </a-timeline-item>
            </a-timeline>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
  <a-modal v-model:visible="visible" :width="600" :title="fileTitle"  @ok="handleOk">
    <a-form :model="fileformState" labelAlign="left" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter=16>
        <a-col :span="10" :style="{paddingBottom: '10px'}">
          <a-form-item name="dragger" no-style>
            <a-upload-dragger
                v-model:fileList="fileList"
                :action="action"
                :beforeUpload="beforeUpload"
                @change="postFile"
                name="file"
                accept=".pdf, .docx"
            >
              <div class="dragger-img">
                <img src="@/assets/images/ResourceContract/file.png" alt="">
              </div>
              <p class="ant-upload-text" :style="{color: '#2C3749',fontSize: '14px'}">将文件拖到此处，或 <span :style="{color: '#0062AD'}">点击上传</span> </p>
              <p class="ant-upload-hint" :style="{color: '#6B7A8B', fontSize: '12px'}" >支持pdf,docx格式</p>
            </a-upload-dragger>
          </a-form-item>
        </a-col>
        <a-col :span="14">
          <div class="form-item-border">
            <a-form-item label="附件名称" name="fileName" :rules="[{ required: true, message: '请输入附件名称' }]">
              <a-input :bordered="false" v-model:value="fileformState.fileName" placeholder="默认文件名称"/>
            </a-form-item>
          </div>
          <div class="form-item-border" :style="{height: '50%'}">
            <a-form-item label="备注" name="remark">
              <a-textarea :bordered="false" autoSize v-model:value="fileformState.remark" placeholder="请输入备注" :rows="3"/>
            </a-form-item>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <div class="from-btn-right">
        <a-button key="back" class="border-btn" @click="colseFileModel">取消</a-button>
        <a-button key="submit" @click="handleOk" class="search-btn1">保存</a-button>
      </div>
    </template>
  </a-modal>
  <a-modal v-model:visible="wordvisible" :width="800" :bodyStyle="bodyStyle" :footer="null" title="合同预览"  @ok="wordhandleOk">
    <PdfPreview v-if="viewType === 'pdf'" :pdf-url="jsPdf"/>
    <WordView v-if="viewType === 'docx'" :word-url="jsPdf"/>
  </a-modal>
</div>
</template>

<script setup>
import {getCurrentInstance, ref, onMounted, watch} from "vue";
const { proxy  } = getCurrentInstance()
import { useRoute, useRouter } from 'vue-router';
import { SearchOutlined, CloseCircleFilled, DeleteOutlined, CloudUploadOutlined,TagsOutlined, EyeOutlined,QuestionCircleOutlined, EditOutlined } from '@ant-design/icons-vue';
const jsPdf = ref('')
import PdfPreview from '@/components/PdfView/PdfPreview.vue'
import WordView from '@/components/WordView/WordView.vue'
import EmptyDefault from '@/components/EmptyDefault/EmptyDefault.vue'
import PdfTestInfo from './PdfTestInfo.vue'
import ContractDecriptions from './ContractDecriptions.vue'
import MianContractDecriptions from './MianContractDecriptions.vue'
import {BASE_URL} from "@/config/proxyIp";
import {message} from "ant-design-vue";
const router = useRouter()
const route = useRoute()
const tabs = ref(route.query.tab?route.query.tab : '1')
const resultObjData = ref({}) // 可编辑的字段
const originalContract = ref({}) //合同原件
const filesData = ref([]) // 合同附件
const timelineData = ref([]) // 合同状态
const contractLabels = ref([]) // 合同标签
const mainMemoradumData = ref([]) // 主合同下的备忘录表格
const contractLabelsSearch = ref([])
const searchLabel = ref('')
const tableTile = ref('资金结算')
const visible = ref(false);
const fileList = ref([])
const action = ref(`${BASE_URL}/con/common/upload`)
const activeKey = ref('1')
const bodyStyle = ref({
  height: '800px',
  overflow: 'auto'
})
const mainColums = ref([
  {
    title: '序号',
    dataIndex: 'num',
    key: 'num',
    width: '80px',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '合同名称',
    dataIndex: 'contractName',
    key: 'contractName',
    fixed: 'left',
    width: '150px',
    align: 'center'
  },
  {
    title: '合同编号',
    dataIndex: 'contractNumber',
    key: 'contractNumber',
    width: '150px',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '买方',
    dataIndex: 'buyer',
    key: 'buyer',
    width: '150px',
    align: 'center'
  },
  {
    title: '卖方',
    dataIndex: 'seller',
    key: 'seller',
    width: '150px',
    align: 'center'
  },
  {
    title: '贸易主体',
    dataIndex: 'tradeBody',
    key: 'tradeBody',
    width: '150px',
    align: 'center'
  },
  {
    title: '交付方式',
    dataIndex: 'deliveryType',
    key: 'deliveryType',
    width: '150px',
    align: 'center'
  },
  {
    title: '操作',
    key: 'tags',
    fixed: 'right',
    align: 'center',
    width: '100px'
  }
])
const columns = ref([
  {
    title: '序号',
    dataIndex: 'a1',
    key: 'a1',
    width: '80px',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '订单编号',
    dataIndex: 'a2',
    key: 'a2',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '订单类型',
    dataIndex: 'a3',
    key: 'a3',
    fixed: 'left',
    align: 'center'
  },
  {
    title: '订单金额',
    dataIndex: 'a4',
    align: 'center'
  },
  {
    title: '对方账户名称',
    dataIndex: 'a5',
    align: 'center'
  },
  {
    title: '对方银行地址',
    dataIndex: 'a6',
    align: 'center'
  },
  {
    title: 'SWIFT Code/BIC',
    dataIndex: 'a7',
    align: 'center'
  },
  {
    title: '申请人',
    dataIndex: 'a8',
    align: 'center'
  },
  {
    title: '申请时间',
    dataIndex: 'a9',
    align: 'center'
  },
  {
    title: '支付时间',
    dataIndex: 'a10',
    align: 'center'
  }, {
    title: '支付状态',
    dataIndex: 'a11',
    align: 'center'
  },

])
const data = ref([])
const fileTitle = ref('上传合同附件')
const labelCol = ref(
    {
      style: {
        width: '100px'
      },
    },
)

const wrapperCol = ref({
  span: 20
})
const formState = ref({
  conId: route.query.id,
  url: '',
  fileName: '',
  remark: ''
})
// 贸易主体
const tradeareas = ref([
  {
    label: '国贸',
    value: 1
  },
  {
    label: '新贸',
    value: 2
  },
])
//交货方式
const wayareas = ref([
  {
    label: 'FOB',
    value: 1
  },
  {
    label: 'DES',
    value: 2
  },
])
const fileformState = ref({
  conId: route.query.id,
  url: '',
  fileName: '',
  remark: ''
})
watch(() => resultObjData.value, (newVal) => {
  console.log('数据更新了编辑信息', newVal)
  resultObjData.value = newVal
},{
  deep: true
} )
watch(() => originalContract.value, (newVal) => {
  console.log('数据更新了合同原件信息', newVal)
  originalContract.value = newVal
},{
  deep: true
} )
watch(() => contractLabels.value, (newVal) => {
  console.log('数据更新了标签信息', newVal)
  contractLabels.value = newVal
  contractLabelsSearch.value = newVal
},{
  deep: true
} )
watch(() => filesData.value, (newVal) => {
  console.log('数据更新了合同附件信息', newVal)
  filesData.value = newVal
},{
  deep: true
} )
watch(() => route.query.tab, (newVal) => {
  console.log('数据更新了合同原件信息', newVal)
  tabs.value = newVal
  getInfoDetails()
},{
  deep: true
})
const wordvisible = ref(false)
const viewType = ref('')
const showWordhandleOk = (url) => {
  console.log('点击了没', url)
  wordvisible.value = true
  let houzui = url.substring(url.lastIndexOf('.'), url.length).toLowerCase()
  let res1 = ['.pdf'].includes(houzui)
  if (res1) {
    viewType.value = 'pdf'
  } else {
    viewType.value = 'docx'
  }
  jsPdf.value = url
}
const wordhandleOk = () => {
  wordvisible.value = false
}
/**
 * 保存标签后，更新数据
 * */
const onSaveLabel = (val) => {
  if (val) {
    getInfoDetails()
    activeKey.value = '2'
  }
}
/**
 * 定位标签
 * */
const posionInfo = ref({})
const lablePosion = (item) => {
  posionInfo.value = item
}
/**
 * 删除合同标签
 * */
const deleteLable = (item) => {
  proxy.$api.deletwContranctLabels({id: item.id.toString(), conId: item.conId.toString()}).then(res => {
    if (res.resultCode === 0) {
      message.success('删除成功')
      getInfoDetails()
    }
  })
}
/**
 * 获取主合同详情
 * */
const getInfoDetails = () => {
  filesData.value = []
  if (route.query.tab === '1') {
    proxy.$api.getMemorandumInfo({id: route.query.id}).then(res => {
      console.log('备忘录详情', res)
      resultObjData.value = res.resultObject.data
      let newFilesData =  res.resultObject.files
      if (newFilesData.length > 0) {
        newFilesData.map(item => {
          if(item.fileType === 1) {
            Object.assign(item, {
              contractName: resultObjData.value.contractName
            })
            originalContract.value = item
          } else {
            filesData.value.push(item)
          }
        })
      }
      timelineData.value = res.resultObject.optRecord
      contractLabels.value = res.resultObject.contractLabels
    }).catch(err => {
      console.log('请求的错误', err)
    })
  } else if (route.query.tab === '2') {
    tableTile.value = '备忘录'
    proxy.$api.getResoureMainInfo({id: route.query.id}).then(res => {
      console.log('获取合同详情', res)
      resultObjData.value = res.resultObject.data
      let newFilesData =  res.resultObject.files
      if (newFilesData.length > 0) {
        newFilesData.map(item => {
          if(item.fileType === 1) {
            Object.assign(item, {
              contractName: resultObjData.value.contractName
            })
            originalContract.value = item
          } else {
            filesData.value.push(item)
          }
        })
      }
      timelineData.value = res.resultObject.optRecord
      contractLabels.value = res.resultObject.contractLabels
      mainMemoradumData.value = res.resultObject.memorandum
      if (mainMemoradumData.value && mainMemoradumData.value.length > 0) {
        mainMemoradumData.value.map((item, index) => {
          Object.assign(item, {
            num: index + 1
          })
        })
      }

    })
  }
}
/**
 * 文件上传
 * */
const postFile = (info) => {
  console.log('上传文件1', info)
  const status = info.file.status
  console.log('上传文件状态', status)
  if (status === 'done') {
    console.log('上传文件信息441', info)
    fileformState.value.fileName = info.file.name
    fileformState.value.url = info.file.response.resultObject
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传失败`);
  }
  console.log('上传文件信息1', fileformState.value)
}
const beforeUpload = (file) => {
  console.log('上传文件2', file)
  let houzui = file.name.substring(file.name.lastIndexOf('.'), file.name.length).toLowerCase()
  let res = ['.pdf','.docx'].includes(houzui)
  // '.doc', '.docx'
  if (!res) {
    fileList.value = []
    message.error('请上传PDF或者docx文件')
  }
  return res

}
/**
 * 合同附件表单提交
 * */
const showModal = () => {
  visible.value = true
  fileformState.value = {
    conId: route.query.id,
    url: '',
    fileName: '',
    remark: ''
  }
  fileList.value = []
};
const colseFileModel = () => {
  visible.value = false
}
const handleOk = () => {
  if (fileTitle.value === '上传合同附件') {
    proxy.$api.postUploadContractFiles(fileformState.value).then(res => {
      console.log('上传合同附件成功', res)
      visible.value = false;
      message.success('上传附件成功')
      getInfoDetails()
    })
  } else {
    proxy.$api.putUploadContractFiles(fileformState.value).then(res => {
      console.log('修改合同附件成功', res)
      visible.value = false;
      message.success('修改附件成功')
      getInfoDetails()
    })
  }

};
/**
 * 编辑合同附件
 * */
const editFile = (item) => {
  fileTitle.value = '编辑合同附件'
  visible.value = true
  fileformState.value = item
  fileList.value = []
  let obj = {
    uid:item.conId,
    name: item.fileName,
    status: 'done'
  }
  fileList.value.push(obj)
}
/**
 * 下载附件
 * */
const dowloadFile = (url) => {
  window.location.href = url
}
/**
 * 删除附件
 * */
const deleteFileConfirm = (item) => {
  console.log('删除的id', item.id.toString())
 proxy.$api.deleteUploadContractFiles({id: item.id.toString(),conId: item.conId.toString()}).then(_ => {
   message.success('删除成功')
   getInfoDetails()
 })
}
/**
 * 搜索的文字
 * */
const searchInfo = ref({})
const searchTxtPostion = (val) => {
  console.log('我拿到的搜索的值', val)
  searchInfo.value = val
}
const onSaveEdit = (val) => {
  if (val) {
    isEdit.value = false
    isSave.value = true
    getInfoDetails()
  }
}
/**
 * 获取主合同的表格
 * */
const getMainDetails = () => {
}
/**
 * 获取备忘录详情中的表格
 * */
const getMemorandum = () => {}
/**
 * 备忘录查看
 * */
const goInfo = ()=> {
  router.push({
    path: '/AContractInfo',
    query: {
      tab: '1'
    },
  })
}
/**
 * 搜索标签
 * */
const onSearchLabel = () => {
  if (searchLabel.value) {
    console.log('搜索了没', searchLabel.value);
    let arrLabel = ['labelValue']
    let testLabel = contractLabels.value.filter((item) => {
      for (let i = 0; i < arrLabel.length; i++) {
        if (item[arrLabel[i]] !== undefined || item[arrLabel[i]] !== null) {
          if (item[arrLabel[i]].indexOf(searchLabel.value) >= 0) {
            return item
          }
        }
      }
    })
    console.log('模糊查了没', testLabel)
    contractLabelsSearch.value = testLabel
  } else {
    contractLabelsSearch.value = contractLabels.value
  }
}
const changeRadio = (e) => {
  activeKey.value = e.target.value
  searchLabel.value = ''
  getInfoDetails()
}
const isEdit = ref(false)
const isSave = ref(false)
// const isSubmit = ref(false)
const editClick = () => {
  isEdit.value = true
  isSave.value = false
}
const cancelClick = () => {
  isEdit.value = false
  isSave.value = false
}
const saveClick = () => {
  isSave.value = true
}
onMounted(() => {
  console.log('route.query', route.query)
  getInfoDetails()
  isEdit.value = false
})

</script>

<style lang="scss" scoped>
.dragger-img {
  img {
    width: 164px;
    height: 114px;
  }
}
.table-btn-flex {
  display: flex;
  justify-content: space-between;
  width: 100%;
  padding: 10px 18px;
  background: #fff;
  .ant-radio-button-wrapper-checked {
    background: #0062AD;
    color: #ffffff;
  }
  .pdf-info-btn {
    margin-top: 10px;
  }
}
</style>
